package com.zgkxzx.java.mutilThread;

import android.util.Log;


import com.zgkxzx.java.mutilThread.myLock.MyLock;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 创建者 zgkxzx
 * 日期   12/28/17
 * 描述
 */

public class Account {
    private int balance;
    private String name;
    //重入锁
    private Lock lock = new ReentrantLock();
    //信号量
    private Semaphore semaphore = new Semaphore(1);

    private Object object = new Object();

    private MyLock myLock = new MyLock();


    public Account(int balance) {
        this.balance = balance;
    }


    /**
     * 未保护的
     *
     * @param money
     */
    public void add(String name, int money) {
        this.name = name;
        balance += money;
        handleMoney();
    }

    /**
     * 使用synchronized代码块同步
     *
     * @param money
     */
    public void add4(String name, int money) {
        synchronized (object) {
            this.name = name;
            balance += money;
            handleMoney();
        }
    }

    /**
     * 使用synchronized 来进行线程同步
     *
     * @param money
     */
    public synchronized void add1(String name, int money) {
        this.name = name;
        balance += money;
        handleMoney();
    }

    /**
     * 使用重入锁进行同步
     *
     * @param money
     */
    public void add2(String name, int money) {
        lock.lock();
        this.name = name;
        balance += money;
        handleMoney();
        lock.unlock();
    }


    /**
     * 使用自定义锁进行同步
     *
     * @param money
     */
    public void add5(String name, int money) {
        myLock.lock();
        this.name = name;
        balance += money;
        handleMoney();
        myLock.unlock();
    }

    /**
     * 使用信号量进行同步
     *
     * @param money
     */
    public void add3(String name, int money) throws InterruptedException {
        semaphore.acquire();
        this.name = name;
        balance += money;
        handleMoney();
        semaphore.release();

    }


    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

    private void handleMoney() {
        try {
            TimeUnit.MILLISECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.d("Thread ", "线程 " + name + " 存入后为" + balance);
    }
}
